﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.BLL.FactoryTool;
using MINERP.MODEL.FactoryTool;

using Leadtools.Codecs;
using Leadtools;
using MINERP.MODEL.FoundationModel;
using MINERP.ComControls;
using MINERP.COM;

namespace MINERP.FactoryTool.Forms
{
    public partial class FrmStartFactory : FrmParent
    {
        public FrmStartFactory()
        {
            InitializeComponent();
        }

        private void FrmStartFactory_Load(object sender, EventArgs e)
        {
            List<FactorySubOrderDescription_Info> list = _bll.GetAllDes();
            foreach (FactorySubOrderDescription_Info fsod in list)
            {
                ((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)repositoryItemComboBoxType).Items.Add(fsod.SubOrderDesDetail);
            }
            userid = base.userId;
        }

        FastReport.Report reportChaiFen = new FastReport.Report();
        FactoryToolBLL _bll = new FactoryToolBLL();
        FTOrderInfo_Info CurrentftOrder = new FTOrderInfo_Info();
        private void textEditBarcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == (int)Keys.Enter)
            {

                string barcode = textEditBarcode.Text.Trim();
                int Orderid = 0;
                if (barcode.Length == 10)
                {
                    Orderid = Convert.ToInt32(barcode = barcode.Trim('2').Trim('0'));

                }
                else
                {
                    Orderid = Convert.ToInt32(barcode);
                }

                CurrentftOrder = _bll.GetOrderInfo(Orderid);
                if (CurrentftOrder != null)
                {
                    if (CurrentftOrder.intProductStatus == (int)OutProcessRecordStatus.Outing)
                    {
                    }
                    else if (CurrentftOrder.intProductStatus == (int)OutProcessRecordStatus.Fetched)
                    {
                        if (MessageBox.Show("该产品已经制作完成是否继续？", "确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {

                        }
                        else
                        {
                            return;
                        }
                    }
                    else if (CurrentftOrder.intProductStatus == (int)OutProcessRecordStatus.InGrid)
                    {
                        if (MessageBox.Show("该产品在委外格子中是否继续？", "确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {

                        }
                        else
                        {
                            return;
                        }
                    }
                    else if (CurrentftOrder.intProductStatus == (int)OutProcessRecordStatus.OutWaitFenDui)
                    {
                        if (MessageBox.Show("该产品还未打印委外单是否继续？", "确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {

                        }
                        else
                        {
                            return;
                        }
                    }
                    foreach (FSPhotoInfo_Info photo in CurrentftOrder.PhotoList)
                    {
                        if (checkBoxIsdisPlay.Checked)
                        {
                            Image image = Image.FromFile(photo.PicPath);
                            int intHeigth = 80;
                            int intWidth = (80 * image.Width) / image.Height;
                            //Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                            Image imageTh = image.GetThumbnailImage(intWidth, intHeigth, () => { return false; }, IntPtr.Zero);
                            //Image imageTh = GetStampPic(photo.PicPath);
                            photo.PhotoImage = imageTh;
                        }

                    }
                    if (CurrentftOrder.FSubOrderList == null || CurrentftOrder.FSubOrderList.Count == 0)//未拆分过
                    {
                        int subId = 1;
                        foreach (var pis in CurrentftOrder.PhotoList.GroupBy(p => p.PhtotoSizeInch))
                        {
                            FSFactorySubOrderInfo_Info subOrder = new FSFactorySubOrderInfo_Info();
                            subOrder.OrderProductID = CurrentftOrder.OrderProductId;
                            subOrder.SubOrderDesDetail = "请选择或者填写";//产品名称+信息
                            subOrder.SubOrderID = subId;
                            subOrder.CreatUserID = userid;
                            subOrder.Exists = false;

                            CurrentftOrder.FSubOrderList.Add(subOrder);
                            subId++;

                        }
                    }
                    else
                    {
                        //状态显示
                    }
                    labelPageNum.Text = CurrentftOrder.PageNum.ToString();
                    labelProductName.Text = CurrentftOrder.OrderProductName;
                    labelSize.Text = CurrentftOrder.Width + "x" + CurrentftOrder.Height + "in";

                    gridControlSubProduct.DataSource = CurrentftOrder.FSubOrderList.OrderBy(p => p.OrderProductID).ToList();
                    gridControlSubProduct.RefreshDataSource();
                    gridControlPhotoList.DataSource = CurrentftOrder.PhotoList.OrderBy(p => p.PhotoName).ToList();
                    gridControlPhotoList.RefreshDataSource();
                }
                else
                {
                    labelPageNum.Text = "0" ;
                    labelProductName.Text = "产品不在生产中";
                    labelSize.Text = "0x0in";
                    gridControlSubProduct.DataSource = null;
                    gridControlSubProduct.RefreshDataSource();
                    gridControlPhotoList.DataSource =null;
                    gridControlPhotoList.RefreshDataSource();
                }


            }
        }

        public Image GetStampPic(string picPath)
        {
            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
            RasterImage image1 = null;
            CodecsThumbnailOptions options = CodecsThumbnailOptions.Default;
            options.LoadStamp = true;
            options.Resample = true;
            options.MaintainAspectRatio = false;
            try
            {
                image1 = codecs.ReadThumbnail(picPath, options, 1);
                //image1 = codecs.Load(picPath);
            }
            catch
            {
                options.LoadStamp = false;
                image1 = codecs.ReadThumbnail(picPath, options, 1);
            }
            codecs.Dispose();
            RasterCodecs.Shutdown();

            return image1.ChangeToGdiPlusImage(ChangeToGdiPlusImageFlags.ForceChange);
        }
        int userid = 1;
        private void simpleButtonAdd_Click(object sender, EventArgs e)
        {
            int intNextSubId = CurrentftOrder.FSubOrderList.Count + 1;
            CurrentftOrder.FSubOrderList.Add(new FSFactorySubOrderInfo_Info() { OrderProductID = CurrentftOrder.OrderProductId, SubOrderID = intNextSubId, Exists = false, CreatUserID = userid });
            gridControlSubProduct.DataSource = CurrentftOrder.FSubOrderList.OrderBy(p => p.OrderProductID).ToList();
            gridControlSubProduct.RefreshDataSource();
        }

        private void simpleButtonDelete_Click(object sender, EventArgs e)
        {
            FSFactorySubOrderInfo_Info info = (FSFactorySubOrderInfo_Info)layoutViewSubProduct.GetFocusedRow();
            if (DialogResult.OK == MessageBox.Show("确定要删除" + CurrentftOrder.OrderProductName + "的'" + info.SubOrderID + "'号部分？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                if (info.Exists)
                {
                    List<FSFactorySubOrderInfo_Info> listOut = new List<FSFactorySubOrderInfo_Info>();
                    if (_bll.DeleteSubOrder(info, out listOut) > 0)
                    {
                        List<FSFactorySubOrderInfo_Info> UnExist = new List<FSFactorySubOrderInfo_Info>();
                        int startOrder = listOut.Count + 1; ;
                        foreach (FSFactorySubOrderInfo_Info fs in CurrentftOrder.FSubOrderList.Where(p => !p.Exists).ToList())
                        {
                            FSFactorySubOrderInfo_Info fsinfo = new FSFactorySubOrderInfo_Info();
                            fsinfo.OrderProductID = fs.OrderProductID;
                            fsinfo.SubOrderDesDetail = fs.SubOrderDesDetail;
                            fsinfo.SubOrderID = startOrder;
                            listOut.Add(fsinfo);
                            startOrder++;
                        }


                        CurrentftOrder.FSubOrderList = listOut;
                        gridControlSubProduct.DataSource = CurrentftOrder.FSubOrderList.OrderBy(p => p.OrderProductID).ToList();
                        gridControlSubProduct.RefreshDataSource();
                    }
                    else
                    {
                        MessageBox.Show("删除失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {

                    CurrentftOrder.FSubOrderList.Remove(info);
                    int intStart = CurrentftOrder.FSubOrderList.Where(p=>p.Exists).Count();
                   
                    foreach (FSFactorySubOrderInfo_Info fsfsoinfo in CurrentftOrder.FSubOrderList.Where(p=>!p.Exists).OrderBy(p=>p.SubOrderID).ToList())
                    {
                        intStart++;
                        fsfsoinfo.SubOrderID = intStart;

                    }

                    gridControlSubProduct.DataSource = CurrentftOrder.FSubOrderList.OrderBy(p => p.OrderProductID).ToList();
                    gridControlSubProduct.RefreshDataSource();

                }


            }
        }

        private void simpleButtonSure_Click(object sender, EventArgs e)
        {
            foreach (FSFactorySubOrderInfo_Info info in CurrentftOrder.FSubOrderList)
            {

                if (info.SubOrderDesDetail == null || string.IsNullOrEmpty(info.SubOrderDesDetail.Trim()) || info.SubOrderDesDetail.Contains("选择") || info.SubOrderDesDetail.Contains("填写"))
                {
                    MessageBox.Show("请给" + info.SubOrderID + "选择类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

            }
            int rtnInt = _bll.InsertSubOrders(CurrentftOrder);
            //if (rtnInt >= 1)
            {
                string barcode = textEditBarcode.Text.Trim();
                int Orderid = 0;
                if (barcode.Length == 10)
                {
                    Orderid = Convert.ToInt32(barcode = barcode.Trim('2').Trim('0'));

                }
                else
                {
                    Orderid = Convert.ToInt32(barcode);
                }

                CurrentftOrder = _bll.GetOrderInfo(Orderid);
                gridControlSubProduct.DataSource = CurrentftOrder.FSubOrderList.OrderBy(p => p.OrderProductID).ToList();
                gridControlSubProduct.RefreshDataSource();
                MessageBox.Show("拆分成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


        }

        private void layoutViewSubProduct_CustomCardStyle(object sender, DevExpress.XtraGrid.Views.Layout.Events.LayoutViewCardStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                FSFactorySubOrderInfo_Info order = (FSFactorySubOrderInfo_Info)layoutViewSubProduct.GetRow(e.RowHandle);
                if (!order.Exists)
                {
                    e.Appearance.BackColor = Color.LightGreen;
                }
            }
        }

        private void simpleButtonPrint_Click(object sender, EventArgs e)
        {
            foreach (FSFactorySubOrderInfo_Info info in CurrentftOrder.FSubOrderList)
            {

                if (!info.Exists)
                {
                    MessageBox.Show("请先保存还未保存的拆分", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

            }
            foreach (FSFactorySubOrderInfo_Info info in CurrentftOrder.FSubOrderList)
            {
                DataTable table = CreateTable();
                DataRow row = table.NewRow();
                row["OrderProductName"] = CurrentftOrder.OrderProductName;
                row["CtmName"] = CurrentftOrder.CtmName;
                row["OrderProductCode"] = CurrentftOrder.OrderProductId + "-" + info.SubOrderID;
                row["shopName"] = CurrentftOrder.ShopName;
                row["PageNum"] = CurrentftOrder.PageNum;
                row["FetchTime"] = CurrentftOrder.FetchTime;
                table.Rows.Add(row);
                table.TableName = "table";

                table.WriteXml(@"C:\Windows\xmldata\FactoryTool.xml", XmlWriteMode.WriteSchema);
                reportChaiFen.Load(Application.StartupPath + "\\report\\工厂拆分.frx");
                reportChaiFen.PrintSettings.ShowDialog = false;
                //report.Show();
                reportChaiFen.Print();

            }
           
        }
        private DataTable CreateTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("OrderProductName",typeof(string));
            dt.Columns.Add("CtmName", typeof(string));
            dt.Columns.Add("OrderProductCode", typeof(string));
            dt.Columns.Add("shopName", typeof(string));
            dt.Columns.Add("PageNum", typeof(int));
            dt.Columns.Add("FetchTime", typeof(DateTime));
            return dt;
        }

    }
    public class PhotoInfo
    {
        public string Name { get; set; }
        public string Path { get; set; }
        public int ID { get; set; }
        public Image PhotoImage { get; set; }
    }
    public class SubProduct
    {
        public string Name { get; set; }
        public List<PhotoInfo> PhotoList { get; set; }
        public int PicCount { get { return PhotoList.Count; } }
    }
    
}
